import React, { useEffect } from "react";
import PropTypes from "prop-types";

import { debounce } from "../../assets/js/utils";
import { ListWrapper, ListItem } from "./style";

import { connect } from "react-redux";
import { perfectSong, toggleFullScreen } from "../../page/Player/store/action";

const ico = require("../../assets/images/index.png");
function MusicList(props) {
  const { list, isNum, onscroll = {} } = props;
  const { is, callback, fieldHeight = 50 } = onscroll;
  const handleScroll = function(e) {
    const top = document.documentElement.scrollTop;
    const height = document.documentElement.scrollHeight;
    const client = document.documentElement.clientHeight;
    const distance = height - (top + client);
    /** 小于给定的高度，执行回调 */
    if (distance < fieldHeight) {
      callback();
    }
  };
  /** 观察onscroll，伺机启动监听，离开前移除监听 */
  useEffect(() => {
    let fn;
    if (is) {
      /** 此处可用节流 */
      fn = debounce(handleScroll);
      window.addEventListener("scroll", fn, false);
    }
    return () => {
      window.removeEventListener("scroll", fn, false);
    };
  }, [onscroll]);
  const handleClick = song => {
    props.perfectSong(song);
    props.toggleFullScreen(true);
  };
  return (
    <ListWrapper>
      {list.map((item, index) => (
        <ListItem
          ico={ico}
          key={item.id}
          onClick={handleClick.bind(this, item)}
        >
          {isNum ? (
            <div className={index <= 2 ? "num top" : "num normal"}>
              {index < 9 ? "0" + (index + 1) : index + 1}
            </div>
          ) : null}
          <div className="item border-bottom">
            <div className="info">
              <div className="song-name overflow-dot">
                {item.name}
                <span className="song-alia">{item.alias}</span>
              </div>
              <div className="singers overflow-dot">
                <i></i>
                {item.artists}-{item.album.name}
              </div>
            </div>
            <div className="btn">
              <span></span>
            </div>
          </div>
        </ListItem>
      ))}
    </ListWrapper>
  );
}

MusicList.propTypes = {
  list: PropTypes.array.isRequired,
  isNum: PropTypes.bool,
  onscroll: PropTypes.object
};
export default connect(state => ({}), { perfectSong,toggleFullScreen })(React.memo(MusicList));
